home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / urllib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  48KB  |  1,685 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Open an arbitrary URL.
  5.  
  6. See the following document for more info on URLs:
  7. "Names and Addresses, URIs, URLs, URNs, URCs", at
  8. http://www.w3.org/pub/WWW/Addressing/Overview.html
  9.  
  10. See also the HTTP spec (from which the error codes are derived):
  11. "HTTP - Hypertext Transfer Protocol", at
  12. http://www.w3.org/pub/WWW/Protocols/
  13.  
  14. Related standards and specs:
  15. - RFC1808: the "relative URL" spec. (authoritative status)
  16. - RFC1738 - the "URL standard". (authoritative status)
  17. - RFC1630 - the "URI spec". (informational status)
  18.  
  19. The object returned by URLopener().open(file) will differ per
  20. protocol.  All you know is that is has methods read(), readline(),
  21. readlines(), fileno(), close() and info().  The read*(), fileno()
  22. and close() methods work like those of open files.
  23. The info() method returns a mimetools.Message object which can be
  24. used to query various info about the object, if available.
  25. (mimetools.Message objects are queried with the getheader() method.)
  26. '''
  27. import string
  28. import socket
  29. import os
  30. import time
  31. import sys
  32. import base64
  33. import re
  34. from urlparse import urljoin as basejoin
  35. __all__ = [
  36.     'urlopen',
  37.     'URLopener',
  38.     'FancyURLopener',
  39.     'urlretrieve',
  40.     'urlcleanup',
  41.     'quote',
  42.     'quote_plus',
  43.     'unquote',
  44.     'unquote_plus',
  45.     'urlencode',
  46.     'url2pathname',
  47.     'pathname2url',
  48.     'splittag',
  49.     'localhost',
  50.     'thishost',
  51.     'ftperrors',
  52.     'basejoin',
  53.     'unwrap',
  54.     'splittype',
  55.     'splithost',
  56.     'splituser',
  57.     'splitpasswd',
  58.     'splitport',
  59.     'splitnport',
  60.     'splitquery',
  61.     'splitattr',
  62.     'splitvalue',
  63.     'getproxies']
  64. __version__ = '1.17'
  65. MAXFTPCACHE = 10
  66. if os.name == 'nt':
  67.     from nturl2path import url2pathname, pathname2url
  68. elif os.name == 'riscos':
  69.     from rourl2path import url2pathname, pathname2url
  70. else:
  71.     
  72.     def url2pathname(pathname):
  73.         """OS-specific conversion from a relative URL of the 'file' scheme
  74.         to a file system path; not recommended for general use."""
  75.         return unquote(pathname)
  76.  
  77.     
  78.     def pathname2url(pathname):
  79.         """OS-specific conversion from a file system path to a relative URL
  80.         of the 'file' scheme; not recommended for general use."""
  81.         return quote(pathname)
  82.  
  83. _urlopener = None
  84.  
  85. def urlopen(url, data = None, proxies = None):
  86.     '''Create a file-like object for the specified URL to read from.'''
  87.     global _urlopener
  88.     warnpy3k = warnpy3k
  89.     import warnings
  90.     warnpy3k('urllib.urlopen() has been removed in Python 3.0 in favor of urllib2.urlopen()', stacklevel = 2)
  91.     if proxies is not None:
  92.         opener = FancyURLopener(proxies = proxies)
  93.     elif not _urlopener:
  94.         opener = FancyURLopener()
  95.         _urlopener = opener
  96.     else:
  97.         opener = _urlopener
  98.     if data is None:
  99.         return opener.open(url)
  100.     return None.open(url, data)
  101.  
  102.  
  103. def urlretrieve(url, filename = None, reporthook = None, data = None):
  104.     global _urlopener
  105.     if not _urlopener:
  106.         _urlopener = FancyURLopener()
  107.     return _urlopener.retrieve(url, filename, reporthook, data)
  108.  
  109.  
  110. def urlcleanup():
  111.     if _urlopener:
  112.         _urlopener.cleanup()
  113.     _safe_quoters.clear()
  114.     ftpcache.clear()
  115.  
  116.  
  117. try:
  118.     import ssl
  119. except:
  120.     _have_ssl = False
  121.  
  122. _have_ssl = True
  123.  
  124. class ContentTooShortError(IOError):
  125.     
  126.     def __init__(self, message, content):
  127.         IOError.__init__(self, message)
  128.         self.content = content
  129.  
  130.  
  131. ftpcache = { }
  132.  
  133. class URLopener:
  134.     """Class to open URLs.
  135.     This is a class rather than just a subroutine because we may need
  136.     more than one set of global protocol-specific options.
  137.     Note -- this is a base class for those who don't want the
  138.     automatic handling of errors type 302 (relocated) and 401
  139.     (authorization needed)."""
  140.     __tempfiles = None
  141.     version = 'Python-urllib/%s' % __version__
  142.     
  143.     def __init__(self, proxies = None, **x509):
  144.         if proxies is None:
  145.             proxies = getproxies()
  146.         if not hasattr(proxies, 'has_key'):
  147.             raise AssertionError('proxies must be a mapping')
  148.         self.proxies = None
  149.         self.key_file = x509.get('key_file')
  150.         self.cert_file = x509.get('cert_file')
  151.         self.addheaders = [
  152.             ('User-Agent', self.version)]
  153.         self._URLopener__tempfiles = []
  154.         self._URLopener__unlink = os.unlink
  155.         self.tempcache = None
  156.         self.ftpcache = ftpcache
  157.  
  158.     
  159.     def __del__(self):
  160.         self.close()
  161.  
  162.     
  163.     def close(self):
  164.         self.cleanup()
  165.  
  166.     
  167.     def cleanup(self):
  168.         if self._URLopener__tempfiles:
  169.             for file in self._URLopener__tempfiles:
  170.                 
  171.                 try:
  172.                     self._URLopener__unlink(file)
  173.                 continue
  174.                 except OSError:
  175.                     continue
  176.                 
  177.  
  178.             
  179.             del self._URLopener__tempfiles[:]
  180.         if self.tempcache:
  181.             self.tempcache.clear()
  182.  
  183.     
  184.     def addheader(self, *args):
  185.         """Add a header to be used by the HTTP interface only
  186.         e.g. u.addheader('Accept', 'sound/basic')"""
  187.         self.addheaders.append(args)
  188.  
  189.     
  190.     def open(self, fullurl, data = None):
  191.         """Use URLopener().open(file) instead of open(file, 'r')."""
  192.         fullurl = unwrap(toBytes(fullurl))
  193.         fullurl = quote(fullurl, safe = "%/:=&?~#+!$,;'@()*[]|")
  194.         if self.tempcache and fullurl in self.tempcache:
  195.             (filename, headers) = self.tempcache[fullurl]
  196.             fp = open(filename, 'rb')
  197.             return addinfourl(fp, headers, fullurl)
  198.         (urltype, url) = None(fullurl)
  199.         if not urltype:
  200.             urltype = 'file'
  201.         if urltype in self.proxies:
  202.             proxy = self.proxies[urltype]
  203.             (urltype, proxyhost) = splittype(proxy)
  204.             (host, selector) = splithost(proxyhost)
  205.             url = (host, fullurl)
  206.         else:
  207.             proxy = None
  208.         name = 'open_' + urltype
  209.         self.type = urltype
  210.         name = name.replace('-', '_')
  211.         if not hasattr(self, name):
  212.             if proxy:
  213.                 return self.open_unknown_proxy(proxy, fullurl, data)
  214.             return None.open_unknown(fullurl, data)
  215.         
  216.         try:
  217.             if data is None:
  218.                 return getattr(self, name)(url)
  219.             return None(self, name)(url, data)
  220.         except socket.error:
  221.             msg = None
  222.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  223.  
  224.  
  225.     
  226.     def open_unknown(self, fullurl, data = None):
  227.         '''Overridable interface to open unknown URL type.'''
  228.         (type, url) = splittype(fullurl)
  229.         raise IOError, ('url error', 'unknown url type', type)
  230.  
  231.     
  232.     def open_unknown_proxy(self, proxy, fullurl, data = None):
  233.         '''Overridable interface to open unknown URL type.'''
  234.         (type, url) = splittype(fullurl)
  235.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  236.  
  237.     
  238.     def retrieve(self, url, filename = None, reporthook = None, data = None):
  239.         '''retrieve(url) returns (filename, headers) for a local object
  240.         or (tempfilename, headers) for a remote object.'''
  241.         url = unwrap(toBytes(url))
  242.         if self.tempcache and url in self.tempcache:
  243.             return self.tempcache[url]
  244.         (type, url1) = None(url)
  245.         if filename is None:
  246.             if not type or type == 'file':
  247.                 
  248.                 try:
  249.                     fp = self.open_local_file(url1)
  250.                     hdrs = fp.info()
  251.                     fp.close()
  252.                     return (url2pathname(splithost(url1)[1]), hdrs)
  253.                 except IOError:
  254.                     pass
  255.                 
  256.  
  257.         fp = self.open(url, data)
  258.         
  259.         try:
  260.             headers = fp.info()
  261.             if filename:
  262.                 tfp = open(filename, 'wb')
  263.             else:
  264.                 import tempfile as tempfile
  265.                 (garbage, path) = splittype(url)
  266.                 if not path:
  267.                     pass
  268.                 (garbage, path) = splithost('')
  269.                 if not path:
  270.                     pass
  271.                 (path, garbage) = splitquery('')
  272.                 if not path:
  273.                     pass
  274.                 (path, garbage) = splitattr('')
  275.                 suffix = os.path.splitext(path)[1]
  276.                 (fd, filename) = tempfile.mkstemp(suffix)
  277.                 self._URLopener__tempfiles.append(filename)
  278.                 tfp = os.fdopen(fd, 'wb')
  279.             
  280.             try:
  281.                 result = (filename, headers)
  282.                 if self.tempcache is not None:
  283.                     self.tempcache[url] = result
  284.                 bs = 8192
  285.                 size = -1
  286.                 read = 0
  287.                 blocknum = 0
  288.                 if 'content-length' in headers:
  289.                     size = int(headers['Content-Length'])
  290.                 if reporthook:
  291.                     reporthook(blocknum, bs, size)
  292.                 while None:
  293.                     block = fp.read(bs)
  294.                     if block == '':
  295.                         break
  296.                     read += len(block)
  297.                     blocknum += 1
  298.                     if reporthook:
  299.                         reporthook(blocknum, bs, size)
  300.                         continue
  301.                     tfp.close()
  302.                 fp.close()
  303.                 if size >= 0 and read < size:
  304.                     raise ContentTooShortError('retrieval incomplete: got only %i out of %i bytes' % (read, size), result)
  305.                 return result
  306.  
  307.  
  308.  
  309.     
  310.     def open_http(self, url, data = None):
  311.         '''Use HTTP protocol.'''
  312.         import httplib as httplib
  313.         user_passwd = None
  314.         proxy_passwd = None
  315.         if isinstance(url, str):
  316.             (host, selector) = splithost(url)
  317.             if host:
  318.                 (user_passwd, host) = splituser(host)
  319.                 host = unquote(host)
  320.             realhost = host
  321.         else:
  322.             (host, selector) = url
  323.             (proxy_passwd, host) = splituser(host)
  324.             (urltype, rest) = splittype(selector)
  325.             url = rest
  326.             user_passwd = None
  327.             if urltype.lower() != 'http':
  328.                 realhost = None
  329.             else:
  330.                 (realhost, rest) = splithost(rest)
  331.                 if realhost:
  332.                     (user_passwd, realhost) = splituser(realhost)
  333.                 if user_passwd:
  334.                     selector = '%s://%s%s' % (urltype, realhost, rest)
  335.                 if proxy_bypass(realhost):
  336.                     host = realhost
  337.         if not host:
  338.             raise IOError, ('http error', 'no host given')
  339.         if proxy_passwd:
  340.             proxy_passwd = unquote(proxy_passwd)
  341.             proxy_auth = base64.b64encode(proxy_passwd).strip()
  342.         else:
  343.             proxy_auth = None
  344.         if user_passwd:
  345.             user_passwd = unquote(user_passwd)
  346.             auth = base64.b64encode(user_passwd).strip()
  347.         else:
  348.             auth = None
  349.         h = httplib.HTTP(host)
  350.         if data is not None:
  351.             h.putrequest('POST', selector)
  352.             h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  353.             h.putheader('Content-Length', '%d' % len(data))
  354.         else:
  355.             h.putrequest('GET', selector)
  356.         if proxy_auth:
  357.             h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  358.         if auth:
  359.             h.putheader('Authorization', 'Basic %s' % auth)
  360.         if realhost:
  361.             h.putheader('Host', realhost)
  362.         for args in self.addheaders:
  363.             h.putheader(*args)
  364.         
  365.         h.endheaders(data)
  366.         (errcode, errmsg, headers) = h.getreply()
  367.         fp = h.getfile()
  368.         if errcode == -1:
  369.             if fp:
  370.                 fp.close()
  371.             raise IOError, ('http protocol error', 0, 'got a bad status line', None)
  372.         if errcode <= errcode:
  373.             pass
  374.         elif errcode < 300:
  375.             return addinfourl(fp, headers, 'http:' + url, errcode)
  376.         if data is None:
  377.             return self.http_error(url, fp, errcode, errmsg, headers)
  378.         return None.http_error(url, fp, errcode, errmsg, headers, data)
  379.  
  380.     
  381.     def http_error(self, url, fp, errcode, errmsg, headers, data = None):
  382.         '''Handle http errors.
  383.         Derived class can override this, or provide specific handlers
  384.         named http_error_DDD where DDD is the 3-digit error code.'''
  385.         name = 'http_error_%d' % errcode
  386.         if hasattr(self, name):
  387.             method = getattr(self, name)
  388.             if data is None:
  389.                 result = method(url, fp, errcode, errmsg, headers)
  390.             else:
  391.                 result = method(url, fp, errcode, errmsg, headers, data)
  392.             if result:
  393.                 return result
  394.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  395.  
  396.     
  397.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  398.         '''Default error handler: close the connection and raise IOError.'''
  399.         fp.close()
  400.         raise IOError, ('http error', errcode, errmsg, headers)
  401.  
  402.     if _have_ssl:
  403.         
  404.         def open_https(self, url, data = None):
  405.             '''Use HTTPS protocol.'''
  406.             import httplib
  407.             user_passwd = None
  408.             proxy_passwd = None
  409.             if isinstance(url, str):
  410.                 (host, selector) = splithost(url)
  411.                 if host:
  412.                     (user_passwd, host) = splituser(host)
  413.                     host = unquote(host)
  414.                 realhost = host
  415.             else:
  416.                 (host, selector) = url
  417.                 (proxy_passwd, host) = splituser(host)
  418.                 (urltype, rest) = splittype(selector)
  419.                 url = rest
  420.                 user_passwd = None
  421.                 if urltype.lower() != 'https':
  422.                     realhost = None
  423.                 else:
  424.                     (realhost, rest) = splithost(rest)
  425.                     if realhost:
  426.                         (user_passwd, realhost) = splituser(realhost)
  427.                     if user_passwd:
  428.                         selector = '%s://%s%s' % (urltype, realhost, rest)
  429.             if not host:
  430.                 raise IOError, ('https error', 'no host given')
  431.             if proxy_passwd:
  432.                 proxy_passwd = unquote(proxy_passwd)
  433.                 proxy_auth = base64.b64encode(proxy_passwd).strip()
  434.             else:
  435.                 proxy_auth = None
  436.             if user_passwd:
  437.                 user_passwd = unquote(user_passwd)
  438.                 auth = base64.b64encode(user_passwd).strip()
  439.             else:
  440.                 auth = None
  441.             h = httplib.HTTPS(host, 0, key_file = self.key_file, cert_file = self.cert_file)
  442.             if data is not None:
  443.                 h.putrequest('POST', selector)
  444.                 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  445.                 h.putheader('Content-Length', '%d' % len(data))
  446.             else:
  447.                 h.putrequest('GET', selector)
  448.             if proxy_auth:
  449.                 h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  450.             if auth:
  451.                 h.putheader('Authorization', 'Basic %s' % auth)
  452.             if realhost:
  453.                 h.putheader('Host', realhost)
  454.             for args in self.addheaders:
  455.                 h.putheader(*args)
  456.             
  457.             h.endheaders(data)
  458.             (errcode, errmsg, headers) = h.getreply()
  459.             fp = h.getfile()
  460.             if errcode == -1:
  461.                 if fp:
  462.                     fp.close()
  463.                 raise IOError, ('http protocol error', 0, 'got a bad status line', None)
  464.             if errcode <= errcode:
  465.                 pass
  466.             elif errcode < 300:
  467.                 return addinfourl(fp, headers, 'https:' + url, errcode)
  468.             if data is None:
  469.                 return self.http_error(url, fp, errcode, errmsg, headers)
  470.             return None.http_error(url, fp, errcode, errmsg, headers, data)
  471.  
  472.     
  473.     def open_file(self, url):
  474.         '''Use local file or FTP depending on form of URL.'''
  475.         if not isinstance(url, str):
  476.             raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
  477.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  478.             return self.open_ftp(url)
  479.         return None.open_local_file(url)
  480.  
  481.     
  482.     def open_local_file(self, url):
  483.         '''Use local file.'''
  484.         import mimetypes as mimetypes
  485.         import mimetools as mimetools
  486.         import email.utils as email
  487.         
  488.         try:
  489.             StringIO = StringIO
  490.             import cStringIO
  491.         except ImportError:
  492.             StringIO = StringIO
  493.             import StringIO
  494.  
  495.         (host, file) = splithost(url)
  496.         localname = url2pathname(file)
  497.         
  498.         try:
  499.             stats = os.stat(localname)
  500.         except OSError:
  501.             e = None
  502.             raise IOError(e.errno, e.strerror, e.filename)
  503.  
  504.         size = stats.st_size
  505.         modified = email.utils.formatdate(stats.st_mtime, usegmt = True)
  506.         mtype = mimetypes.guess_type(url)[0]
  507.         if not mtype:
  508.             pass
  509.         headers = mimetools.Message(StringIO('Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  510.         if not host:
  511.             urlfile = file
  512.             if file[:1] == '/':
  513.                 urlfile = 'file://' + file
  514.             elif file[:2] == './':
  515.                 raise ValueError('local file url may start with / or file:. Unknown url of type: %s' % url)
  516.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  517.         (host, port) = None(host)
  518.         if not port and socket.gethostbyname(host) in (localhost(), thishost()):
  519.             urlfile = file
  520.             if file[:1] == '/':
  521.                 urlfile = 'file://' + file
  522.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  523.         raise None, ('local file error', 'not on local host')
  524.  
  525.     
  526.     def open_ftp(self, url):
  527.         '''Use FTP protocol.'''
  528.         if not isinstance(url, str):
  529.             raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
  530.         import mimetypes
  531.         import mimetools
  532.         
  533.         try:
  534.             StringIO = StringIO
  535.             import cStringIO
  536.         except ImportError:
  537.             StringIO = StringIO
  538.             import StringIO
  539.  
  540.         (host, path) = splithost(url)
  541.         if not host:
  542.             raise IOError, ('ftp error', 'no host given')
  543.         (host, port) = splitport(host)
  544.         (user, host) = splituser(host)
  545.         if user:
  546.             (user, passwd) = splitpasswd(user)
  547.         else:
  548.             passwd = None
  549.         host = unquote(host)
  550.         if not user:
  551.             pass
  552.         user = ''
  553.         if not passwd:
  554.             pass
  555.         passwd = ''
  556.         host = socket.gethostbyname(host)
  557.         if not port:
  558.             import ftplib as ftplib
  559.             port = ftplib.FTP_PORT
  560.         else:
  561.             port = int(port)
  562.         (path, attrs) = splitattr(path)
  563.         path = unquote(path)
  564.         dirs = path.split('/')
  565.         dirs = dirs[:-1]
  566.         file = dirs[-1]
  567.         if dirs and not dirs[0]:
  568.             dirs = dirs[1:]
  569.         if dirs and not dirs[0]:
  570.             dirs[0] = '/'
  571.         key = (user, host, port, '/'.join(dirs))
  572.         if len(self.ftpcache) > MAXFTPCACHE:
  573.             for k in self.ftpcache.keys():
  574.                 if k != key:
  575.                     v = self.ftpcache[k]
  576.                     del self.ftpcache[k]
  577.                     v.close()
  578.                     continue
  579.         
  580.         try:
  581.             if key not in self.ftpcache:
  582.                 self.ftpcache[key] = ftpwrapper(user, passwd, host, port, dirs)
  583.             if not file:
  584.                 type = 'D'
  585.             else:
  586.                 type = 'I'
  587.             for attr in attrs:
  588.                 (attr, value) = splitvalue(attr)
  589.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  590.                     type = value.upper()
  591.                     continue
  592.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  593.             mtype = mimetypes.guess_type('ftp:' + url)[0]
  594.             headers = ''
  595.             if mtype:
  596.                 headers += 'Content-Type: %s\n' % mtype
  597.             if retrlen is not None and retrlen >= 0:
  598.                 headers += 'Content-Length: %d\n' % retrlen
  599.             headers = mimetools.Message(StringIO(headers))
  600.             return addinfourl(fp, headers, 'ftp:' + url)
  601.         except ftperrors():
  602.             msg = None
  603.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  604.  
  605.  
  606.     
  607.     def open_data(self, url, data = None):
  608.         '''Use "data" URL.'''
  609.         if not isinstance(url, str):
  610.             raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
  611.         import mimetools
  612.         
  613.         try:
  614.             StringIO = StringIO
  615.             import cStringIO
  616.         except ImportError:
  617.             StringIO = StringIO
  618.             import StringIO
  619.  
  620.         
  621.         try:
  622.             (type, data) = url.split(',', 1)
  623.         except ValueError:
  624.             raise IOError, ('data error', 'bad data URL')
  625.  
  626.         if not type:
  627.             type = 'text/plain;charset=US-ASCII'
  628.         semi = type.rfind(';')
  629.         if semi >= 0 and '=' not in type[semi:]:
  630.             encoding = type[semi + 1:]
  631.             type = type[:semi]
  632.         else:
  633.             encoding = ''
  634.         msg = []
  635.         msg.append('Date: %s' % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time())))
  636.         msg.append('Content-type: %s' % type)
  637.         if encoding == 'base64':
  638.             data = base64.decodestring(data)
  639.         else:
  640.             data = unquote(data)
  641.         msg.append('Content-Length: %d' % len(data))
  642.         msg.append('')
  643.         msg.append(data)
  644.         msg = '\n'.join(msg)
  645.         f = StringIO(msg)
  646.         headers = mimetools.Message(f, 0)
  647.         return addinfourl(f, headers, url)
  648.  
  649.  
  650.  
  651. class FancyURLopener(URLopener):
  652.     '''Derived class with handlers for errors we can handle (perhaps).'''
  653.     
  654.     def __init__(self, *args, **kwargs):
  655.         URLopener.__init__(self, *args, **kwargs)
  656.         self.auth_cache = { }
  657.         self.tries = 0
  658.         self.maxtries = 10
  659.  
  660.     
  661.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  662.         """Default error handling -- don't raise an exception."""
  663.         return addinfourl(fp, headers, 'http:' + url, errcode)
  664.  
  665.     
  666.     def http_error_302(self, url, fp, errcode, errmsg, headers, data = None):
  667.         '''Error 302 -- relocated (temporarily).'''
  668.         self.tries += 1
  669.         if self.maxtries and self.tries >= self.maxtries:
  670.             self.tries = 0
  671.             return meth(url, fp, 500, 'Internal Server Error: Redirect Recursion', headers)
  672.         result = self.redirect_internal(url, fp, errcode, errmsg, headers, data)
  673.         self.tries = 0
  674.         return result
  675.  
  676.     
  677.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  678.         if 'location' in headers:
  679.             newurl = headers['location']
  680.         elif 'uri' in headers:
  681.             newurl = headers['uri']
  682.         else:
  683.             return None
  684.         None.close()
  685.         newurl = basejoin(self.type + ':' + url, newurl)
  686.         newurl_lower = newurl.lower()
  687.         if not newurl_lower.startswith('http://') and newurl_lower.startswith('https://') or newurl_lower.startswith('ftp://'):
  688.             raise IOError('redirect error', errcode, errmsg + " - Redirection to url '%s' is not allowed" % newurl, headers)
  689.         return self.open(newurl)
  690.  
  691.     
  692.     def http_error_301(self, url, fp, errcode, errmsg, headers, data = None):
  693.         '''Error 301 -- also relocated (permanently).'''
  694.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  695.  
  696.     
  697.     def http_error_303(self, url, fp, errcode, errmsg, headers, data = None):
  698.         '''Error 303 -- also relocated (essentially identical to 302).'''
  699.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  700.  
  701.     
  702.     def http_error_307(self, url, fp, errcode, errmsg, headers, data = None):
  703.         '''Error 307 -- relocated, but turn POST into error.'''
  704.         if data is None:
  705.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  706.         return None.http_error_default(url, fp, errcode, errmsg, headers)
  707.  
  708.     
  709.     def http_error_401(self, url, fp, errcode, errmsg, headers, data = None):
  710.         '''Error 401 -- authentication required.
  711.         This function supports Basic authentication only.'''
  712.         if 'www-authenticate' not in headers:
  713.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  714.         stuff = headers['www-authenticate']
  715.         import re as re
  716.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  717.         if not match:
  718.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  719.         (scheme, realm) = match.groups()
  720.         if scheme.lower() != 'basic':
  721.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  722.         name = 'retry_' + self.type + '_basic_auth'
  723.         if data is None:
  724.             return getattr(self, name)(url, realm)
  725.         return None(self, name)(url, realm, data)
  726.  
  727.     
  728.     def http_error_407(self, url, fp, errcode, errmsg, headers, data = None):
  729.         '''Error 407 -- proxy authentication required.
  730.         This function supports Basic authentication only.'''
  731.         if 'proxy-authenticate' not in headers:
  732.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  733.         stuff = headers['proxy-authenticate']
  734.         import re
  735.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  736.         if not match:
  737.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  738.         (scheme, realm) = match.groups()
  739.         if scheme.lower() != 'basic':
  740.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  741.         name = 'retry_proxy_' + self.type + '_basic_auth'
  742.         if data is None:
  743.             return getattr(self, name)(url, realm)
  744.         return None(self, name)(url, realm, data)
  745.  
  746.     
  747.     def retry_proxy_http_basic_auth(self, url, realm, data = None):
  748.         (host, selector) = splithost(url)
  749.         newurl = 'http://' + host + selector
  750.         proxy = self.proxies['http']
  751.         (urltype, proxyhost) = splittype(proxy)
  752.         (proxyhost, proxyselector) = splithost(proxyhost)
  753.         i = proxyhost.find('@') + 1
  754.         proxyhost = proxyhost[i:]
  755.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  756.         if not user or passwd:
  757.             return None
  758.         proxyhost = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  759.         self.proxies['http'] = 'http://' + proxyhost + proxyselector
  760.         if data is None:
  761.             return self.open(newurl)
  762.         return None.open(newurl, data)
  763.  
  764.     
  765.     def retry_proxy_https_basic_auth(self, url, realm, data = None):
  766.         (host, selector) = splithost(url)
  767.         newurl = 'https://' + host + selector
  768.         proxy = self.proxies['https']
  769.         (urltype, proxyhost) = splittype(proxy)
  770.         (proxyhost, proxyselector) = splithost(proxyhost)
  771.         i = proxyhost.find('@') + 1
  772.         proxyhost = proxyhost[i:]
  773.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  774.         if not user or passwd:
  775.             return None
  776.         proxyhost = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  777.         self.proxies['https'] = 'https://' + proxyhost + proxyselector
  778.         if data is None:
  779.             return self.open(newurl)
  780.         return None.open(newurl, data)
  781.  
  782.     
  783.     def retry_http_basic_auth(self, url, realm, data = None):
  784.         (host, selector) = splithost(url)
  785.         i = host.find('@') + 1
  786.         host = host[i:]
  787.         (user, passwd) = self.get_user_passwd(host, realm, i)
  788.         if not user or passwd:
  789.             return None
  790.         host = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  791.         newurl = 'http://' + host + selector
  792.         if data is None:
  793.             return self.open(newurl)
  794.         return None.open(newurl, data)
  795.  
  796.     
  797.     def retry_https_basic_auth(self, url, realm, data = None):
  798.         (host, selector) = splithost(url)
  799.         i = host.find('@') + 1
  800.         host = host[i:]
  801.         (user, passwd) = self.get_user_passwd(host, realm, i)
  802.         if not user or passwd:
  803.             return None
  804.         host = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  805.         newurl = 'https://' + host + selector
  806.         if data is None:
  807.             return self.open(newurl)
  808.         return None.open(newurl, data)
  809.  
  810.     
  811.     def get_user_passwd(self, host, realm, clear_cache = 0):
  812.         key = realm + '@' + host.lower()
  813.         if key in self.auth_cache:
  814.             if clear_cache:
  815.                 del self.auth_cache[key]
  816.             else:
  817.                 return self.auth_cache[key]
  818.         (user, passwd) = self.prompt_user_passwd(host, realm)
  819.         if user or passwd:
  820.             self.auth_cache[key] = (user, passwd)
  821.         return (user, passwd)
  822.  
  823.     
  824.     def prompt_user_passwd(self, host, realm):
  825.         '''Override this in a GUI environment!'''
  826.         import getpass as getpass
  827.         
  828.         try:
  829.             user = raw_input('Enter username for %s at %s: ' % (realm, host))
  830.             passwd = getpass.getpass('Enter password for %s in %s at %s: ' % (user, realm, host))
  831.             return (user, passwd)
  832.         except KeyboardInterrupt:
  833.             print 
  834.             return (None, None)
  835.  
  836.  
  837.  
  838. _localhost = None
  839.  
  840. def localhost():
  841.     """Return the IP address of the magic hostname 'localhost'."""
  842.     global _localhost
  843.     if _localhost is None:
  844.         _localhost = socket.gethostbyname('localhost')
  845.     return _localhost
  846.  
  847. _thishost = None
  848.  
  849. def thishost():
  850.     '''Return the IP address of the current host.'''
  851.     global _thishost
  852.     if _thishost is None:
  853.         
  854.         try:
  855.             _thishost = socket.gethostbyname(socket.gethostname())
  856.         except socket.gaierror:
  857.             _thishost = socket.gethostbyname('localhost')
  858.         
  859.  
  860.     return _thishost
  861.  
  862. _ftperrors = None
  863.  
  864. def ftperrors():
  865.     '''Return the set of errors raised by the FTP class.'''
  866.     global _ftperrors
  867.     if _ftperrors is None:
  868.         import ftplib
  869.         _ftperrors = ftplib.all_errors
  870.     return _ftperrors
  871.  
  872. _noheaders = None
  873.  
  874. def noheaders():
  875.     '''Return an empty mimetools.Message object.'''
  876.     global _noheaders
  877.     if _noheaders is None:
  878.         import mimetools
  879.         
  880.         try:
  881.             StringIO = StringIO
  882.             import cStringIO
  883.         except ImportError:
  884.             StringIO = StringIO
  885.             import StringIO
  886.  
  887.         _noheaders = mimetools.Message(StringIO(), 0)
  888.         _noheaders.fp.close()
  889.     return _noheaders
  890.  
  891.  
  892. class ftpwrapper:
  893.     '''Class used by open_ftp() for cache of open FTP connections.'''
  894.     
  895.     def __init__(self, user, passwd, host, port, dirs, timeout = socket._GLOBAL_DEFAULT_TIMEOUT, persistent = True):
  896.         self.user = user
  897.         self.passwd = passwd
  898.         self.host = host
  899.         self.port = port
  900.         self.dirs = dirs
  901.         self.timeout = timeout
  902.         self.refcount = 0
  903.         self.keepalive = persistent
  904.         self.init()
  905.  
  906.     
  907.     def init(self):
  908.         import ftplib
  909.         self.busy = 0
  910.         self.ftp = ftplib.FTP()
  911.         self.ftp.connect(self.host, self.port, self.timeout)
  912.         self.ftp.login(self.user, self.passwd)
  913.         _target = '/'.join(self.dirs)
  914.         self.ftp.cwd(_target)
  915.  
  916.     
  917.     def retrfile(self, file, type):
  918.         import ftplib
  919.         self.endtransfer()
  920.         if type in ('d', 'D'):
  921.             cmd = 'TYPE A'
  922.             isdir = 1
  923.         else:
  924.             cmd = 'TYPE ' + type
  925.             isdir = 0
  926.         
  927.         try:
  928.             self.ftp.voidcmd(cmd)
  929.         except ftplib.all_errors:
  930.             self.init()
  931.             self.ftp.voidcmd(cmd)
  932.  
  933.         conn = None
  934.         if file and not isdir:
  935.             
  936.             try:
  937.                 cmd = 'RETR ' + file
  938.                 (conn, retrlen) = self.ftp.ntransfercmd(cmd)
  939.             except ftplib.error_perm:
  940.                 reason = None
  941.                 if str(reason)[:3] != '550':
  942.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  943.             
  944.  
  945.         if not conn:
  946.             self.ftp.voidcmd('TYPE A')
  947.             if file:
  948.                 pwd = self.ftp.pwd()
  949.                 
  950.                 try:
  951.                     self.ftp.cwd(file)
  952.                 except ftplib.error_perm:
  953.                     reason = None
  954.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  955.                 finally:
  956.                     self.ftp.cwd(pwd)
  957.  
  958.                 cmd = 'LIST ' + file
  959.             else:
  960.                 cmd = 'LIST'
  961.             (conn, retrlen) = self.ftp.ntransfercmd(cmd)
  962.         self.busy = 1
  963.         ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
  964.         self.refcount += 1
  965.         conn.close()
  966.         return (ftpobj, retrlen)
  967.  
  968.     
  969.     def endtransfer(self):
  970.         if not self.busy:
  971.             return None
  972.         self.busy = None
  973.         
  974.         try:
  975.             self.ftp.voidresp()
  976.         except ftperrors():
  977.             pass
  978.  
  979.  
  980.     
  981.     def close(self):
  982.         self.keepalive = False
  983.         if self.refcount <= 0:
  984.             self.real_close()
  985.  
  986.     
  987.     def file_close(self):
  988.         self.endtransfer()
  989.         self.refcount -= 1
  990.         if self.refcount <= 0 and not (self.keepalive):
  991.             self.real_close()
  992.  
  993.     
  994.     def real_close(self):
  995.         self.endtransfer()
  996.         
  997.         try:
  998.             self.ftp.close()
  999.         except ftperrors():
  1000.             pass
  1001.  
  1002.  
  1003.  
  1004.  
  1005. class addbase:
  1006.     '''Base class for addinfo and addclosehook.'''
  1007.     
  1008.     def __init__(self, fp):
  1009.         self.fp = fp
  1010.         self.read = self.fp.read
  1011.         self.readline = self.fp.readline
  1012.         if hasattr(self.fp, 'readlines'):
  1013.             self.readlines = self.fp.readlines
  1014.         if hasattr(self.fp, 'fileno'):
  1015.             self.fileno = self.fp.fileno
  1016.         else:
  1017.             
  1018.             self.fileno = lambda : pass
  1019.         if hasattr(self.fp, '__iter__'):
  1020.             self.__iter__ = self.fp.__iter__
  1021.             if hasattr(self.fp, 'next'):
  1022.                 self.next = self.fp.next
  1023.             
  1024.  
  1025.     
  1026.     def __repr__(self):
  1027.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
  1028.  
  1029.     
  1030.     def close(self):
  1031.         self.read = None
  1032.         self.readline = None
  1033.         self.readlines = None
  1034.         self.fileno = None
  1035.         if self.fp:
  1036.             self.fp.close()
  1037.         self.fp = None
  1038.  
  1039.  
  1040.  
  1041. class addclosehook(addbase):
  1042.     '''Class to add a close hook to an open file.'''
  1043.     
  1044.     def __init__(self, fp, closehook, *hookargs):
  1045.         addbase.__init__(self, fp)
  1046.         self.closehook = closehook
  1047.         self.hookargs = hookargs
  1048.  
  1049.     
  1050.     def close(self):
  1051.         if self.closehook:
  1052.             self.closehook(*self.hookargs)
  1053.             self.closehook = None
  1054.             self.hookargs = None
  1055.         addbase.close(self)
  1056.  
  1057.  
  1058.  
  1059. class addinfo(addbase):
  1060.     '''class to add an info() method to an open file.'''
  1061.     
  1062.     def __init__(self, fp, headers):
  1063.         addbase.__init__(self, fp)
  1064.         self.headers = headers
  1065.  
  1066.     
  1067.     def info(self):
  1068.         return self.headers
  1069.  
  1070.  
  1071.  
  1072. class addinfourl(addbase):
  1073.     '''class to add info() and geturl() methods to an open file.'''
  1074.     
  1075.     def __init__(self, fp, headers, url, code = None):
  1076.         addbase.__init__(self, fp)
  1077.         self.headers = headers
  1078.         self.url = url
  1079.         self.code = code
  1080.  
  1081.     
  1082.     def info(self):
  1083.         return self.headers
  1084.  
  1085.     
  1086.     def getcode(self):
  1087.         return self.code
  1088.  
  1089.     
  1090.     def geturl(self):
  1091.         return self.url
  1092.  
  1093.  
  1094.  
  1095. try:
  1096.     unicode
  1097. except NameError:
  1098.     
  1099.     def _is_unicode(x):
  1100.         return 0
  1101.  
  1102.  
  1103.  
  1104. def _is_unicode(x):
  1105.     return isinstance(x, unicode)
  1106.  
  1107.  
  1108. def toBytes(url):
  1109.     '''toBytes(u"URL") --> \'URL\'.'''
  1110.     if _is_unicode(url):
  1111.         
  1112.         try:
  1113.             url = url.encode('ASCII')
  1114.         except UnicodeError:
  1115.             raise UnicodeError('URL ' + repr(url) + ' contains non-ASCII characters')
  1116.         
  1117.  
  1118.     return url
  1119.  
  1120.  
  1121. def unwrap(url):
  1122.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  1123.     url = url.strip()
  1124.     if url[:1] == '<' and url[-1:] == '>':
  1125.         url = url[1:-1].strip()
  1126.     if url[:4] == 'URL:':
  1127.         url = url[4:].strip()
  1128.     return url
  1129.  
  1130. _typeprog = None
  1131.  
  1132. def splittype(url):
  1133.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  1134.     global _typeprog
  1135.     if _typeprog is None:
  1136.         import re
  1137.         _typeprog = re.compile('^([^/:]+):')
  1138.     match = _typeprog.match(url)
  1139.     if match:
  1140.         scheme = match.group(1)
  1141.         return (scheme.lower(), url[len(scheme) + 1:])
  1142.     return (None, url)
  1143.  
  1144. _hostprog = None
  1145.  
  1146. def splithost(url):
  1147.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  1148.     global _hostprog
  1149.     if _hostprog is None:
  1150.         import re
  1151.         _hostprog = re.compile('^//([^/?]*)(.*)$')
  1152.     match = _hostprog.match(url)
  1153.     if match:
  1154.         host_port = match.group(1)
  1155.         path = match.group(2)
  1156.         if path and not path.startswith('/'):
  1157.             path = '/' + path
  1158.         return (host_port, path)
  1159.     return (None, url)
  1160.  
  1161. _userprog = None
  1162.  
  1163. def splituser(host):
  1164.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  1165.     global _userprog
  1166.     if _userprog is None:
  1167.         import re
  1168.         _userprog = re.compile('^(.*)@(.*)$')
  1169.     match = _userprog.match(host)
  1170.     if match:
  1171.         return match.group(1, 2)
  1172.     return (None, host)
  1173.  
  1174. _passwdprog = None
  1175.  
  1176. def splitpasswd(user):
  1177.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  1178.     global _passwdprog
  1179.     if _passwdprog is None:
  1180.         import re
  1181.         _passwdprog = re.compile('^([^:]*):(.*)$', re.S)
  1182.     match = _passwdprog.match(user)
  1183.     if match:
  1184.         return match.group(1, 2)
  1185.     return (None, None)
  1186.  
  1187. _portprog = None
  1188.  
  1189. def splitport(host):
  1190.     """splitport('host:port') --> 'host', 'port'."""
  1191.     global _portprog
  1192.     if _portprog is None:
  1193.         import re
  1194.         _portprog = re.compile('^(.*):([0-9]+)$')
  1195.     match = _portprog.match(host)
  1196.     if match:
  1197.         return match.group(1, 2)
  1198.     return (None, None)
  1199.  
  1200. _nportprog = None
  1201.  
  1202. def splitnport(host, defport = -1):
  1203.     """Split host and port, returning numeric port.
  1204.     Return given default port if no ':' found; defaults to -1.
  1205.     Return numerical port if a valid number are found after ':'.
  1206.     Return None if ':' but not a valid number."""
  1207.     global _nportprog
  1208.     if _nportprog is None:
  1209.         import re
  1210.         _nportprog = re.compile('^(.*):(.*)$')
  1211.     match = _nportprog.match(host)
  1212.     if match:
  1213.         (host, port) = match.group(1, 2)
  1214.         
  1215.         try:
  1216.             if not port:
  1217.                 raise ValueError, 'no digits'
  1218.             nport = int(port)
  1219.         except ValueError:
  1220.             nport = None
  1221.  
  1222.         return (host, nport)
  1223.     return (None, defport)
  1224.  
  1225. _queryprog = None
  1226.  
  1227. def splitquery(url):
  1228.     """splitquery('/path?query') --> '/path', 'query'."""
  1229.     global _queryprog
  1230.     if _queryprog is None:
  1231.         import re
  1232.         _queryprog = re.compile('^(.*)\\?([^?]*)$')
  1233.     match = _queryprog.match(url)
  1234.     if match:
  1235.         return match.group(1, 2)
  1236.     return (None, None)
  1237.  
  1238. _tagprog = None
  1239.  
  1240. def splittag(url):
  1241.     """splittag('/path#tag') --> '/path', 'tag'."""
  1242.     global _tagprog
  1243.     if _tagprog is None:
  1244.         import re
  1245.         _tagprog = re.compile('^(.*)#([^#]*)$')
  1246.     match = _tagprog.match(url)
  1247.     if match:
  1248.         return match.group(1, 2)
  1249.     return (None, None)
  1250.  
  1251.  
  1252. def splitattr(url):
  1253.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1254.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1255.     words = url.split(';')
  1256.     return (words[0], words[1:])
  1257.  
  1258. _valueprog = None
  1259.  
  1260. def splitvalue(attr):
  1261.     """splitvalue('attr=value') --> 'attr', 'value'."""
  1262.     global _valueprog
  1263.     if _valueprog is None:
  1264.         import re
  1265.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1266.     match = _valueprog.match(attr)
  1267.     if match:
  1268.         return match.group(1, 2)
  1269.     return (None, None)
  1270.  
  1271. _hexdig = '0123456789ABCDEFabcdef'
  1272. _hextochr = dict((lambda .0: pass)(_hexdig))
  1273. _asciire = re.compile('([\x00-\x7f]+)')
  1274.  
  1275. def unquote(s):
  1276.     """unquote('abc%20def') -> 'abc def'."""
  1277.     if _is_unicode(s):
  1278.         if '%' not in s:
  1279.             return s
  1280.         bits = None.split(s)
  1281.         res = [
  1282.             bits[0]]
  1283.         append = res.append
  1284.         for i in range(1, len(bits), 2):
  1285.             append(unquote(str(bits[i])).decode('latin1'))
  1286.             append(bits[i + 1])
  1287.         
  1288.         return ''.join(res)
  1289.     bits = None.split('%')
  1290.     if len(bits) == 1:
  1291.         return s
  1292.     res = [
  1293.         None[0]]
  1294.     append = res.append
  1295.     for item in bits[1:]:
  1296.         
  1297.         try:
  1298.             append(_hextochr[item[:2]])
  1299.             append(item[2:])
  1300.         continue
  1301.         except KeyError:
  1302.             append('%')
  1303.             append(item)
  1304.             continue
  1305.         
  1306.  
  1307.     
  1308.     return ''.join(res)
  1309.  
  1310.  
  1311. def unquote_plus(s):
  1312.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1313.     s = s.replace('+', ' ')
  1314.     return unquote(s)
  1315.  
  1316. always_safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-'
  1317. _safe_map = { }
  1318. for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
  1319.     _safe_map[c] = c if i < 128 and c in always_safe else '%{:02X}'.format(i)
  1320.  
  1321. _safe_quoters = { }
  1322.  
  1323. def quote(s, safe = '/'):
  1324.     '''quote(\'abc def\') -> \'abc%20def\'
  1325.  
  1326.     Each part of a URL, e.g. the path info, the query, etc., has a
  1327.     different set of reserved characters that must be quoted.
  1328.  
  1329.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1330.     the following reserved characters.
  1331.  
  1332.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1333.                   "$" | ","
  1334.  
  1335.     Each of these characters is reserved in some component of a URL,
  1336.     but not necessarily in all of them.
  1337.  
  1338.     By default, the quote function is intended for quoting the path
  1339.     section of a URL.  Thus, it will not encode \'/\'.  This character
  1340.     is reserved, but in typical usage the quote function is being
  1341.     called on a path where the existing slash characters are used as
  1342.     reserved characters.
  1343.     '''
  1344.     if not s:
  1345.         if s is None:
  1346.             raise TypeError('None object cannot be quoted')
  1347.         return s
  1348.     cachekey = (None, always_safe)
  1349.     
  1350.     try:
  1351.         (quoter, safe) = _safe_quoters[cachekey]
  1352.     except KeyError:
  1353.         safe_map = _safe_map.copy()
  1354.         safe_map.update([ (c, c) for c in safe ])
  1355.         quoter = safe_map.__getitem__
  1356.         safe = always_safe + safe
  1357.         _safe_quoters[cachekey] = (quoter, safe)
  1358.  
  1359.     if not s.rstrip(safe):
  1360.         return s
  1361.     return None.join(map(quoter, s))
  1362.  
  1363.  
  1364. def quote_plus(s, safe = ''):
  1365.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1366.     if ' ' in s:
  1367.         s = quote(s, safe + ' ')
  1368.         return s.replace(' ', '+')
  1369.     return None(s, safe)
  1370.  
  1371.  
  1372. def urlencode(query, doseq = 0):
  1373.     '''Encode a sequence of two-element tuples or dictionary into a URL query string.
  1374.  
  1375.     If any values in the query arg are sequences and doseq is true, each
  1376.     sequence element is converted to a separate parameter.
  1377.  
  1378.     If the query arg is a sequence of two-element tuples, the order of the
  1379.     parameters in the output will match the order of parameters in the
  1380.     input.
  1381.     '''
  1382.     if hasattr(query, 'items'):
  1383.         query = query.items()
  1384.     else:
  1385.         
  1386.         try:
  1387.             if len(query) and not isinstance(query[0], tuple):
  1388.                 raise TypeError
  1389.         except TypeError:
  1390.             (ty, va, tb) = sys.exc_info()
  1391.             raise TypeError, 'not a valid non-string sequence or mapping object', tb
  1392.  
  1393.     l = []
  1394.     if not doseq:
  1395.         for k, v in query:
  1396.             k = quote_plus(str(k))
  1397.             v = quote_plus(str(v))
  1398.             l.append(k + '=' + v)
  1399.         
  1400.     else:
  1401.         for k, v in query:
  1402.             k = quote_plus(str(k))
  1403.             if isinstance(v, str):
  1404.                 v = quote_plus(v)
  1405.                 l.append(k + '=' + v)
  1406.                 continue
  1407.             if _is_unicode(v):
  1408.                 v = quote_plus(v.encode('ASCII', 'replace'))
  1409.                 l.append(k + '=' + v)
  1410.                 continue
  1411.             
  1412.             try:
  1413.                 len(v)
  1414.             except TypeError:
  1415.                 v = quote_plus(str(v))
  1416.                 l.append(k + '=' + v)
  1417.                 continue
  1418.  
  1419.             for elt in v:
  1420.                 l.append(k + '=' + quote_plus(str(elt)))
  1421.             
  1422.         
  1423.     return '&'.join(l)
  1424.  
  1425.  
  1426. def getproxies_environment():
  1427.     '''Return a dictionary of scheme -> proxy server URL mappings.
  1428.  
  1429.     Scan the environment for variables named <scheme>_proxy;
  1430.     this seems to be the standard convention.  If you need a
  1431.     different way, you can pass a proxies dictionary to the
  1432.     [Fancy]URLopener constructor.
  1433.  
  1434.     '''
  1435.     proxies = { }
  1436.     for name, value in os.environ.items():
  1437.         name = name.lower()
  1438.         if value and name[-6:] == '_proxy':
  1439.             proxies[name[:-6]] = value
  1440.             continue
  1441.     return proxies
  1442.  
  1443.  
  1444. def proxy_bypass_environment(host):
  1445.     """Test if proxies should not be used for a particular host.
  1446.  
  1447.     Checks the environment for a variable named no_proxy, which should
  1448.     be a list of DNS suffixes separated by commas, or '*' for all hosts.
  1449.     """
  1450.     if not os.environ.get('no_proxy', ''):
  1451.         pass
  1452.     no_proxy = os.environ.get('NO_PROXY', '')
  1453.     if no_proxy == '*':
  1454.         return 1
  1455.     (hostonly, port) = None(host)
  1456.     no_proxy_list = [ proxy.strip() for proxy in no_proxy.split(',') ]
  1457.     for name in no_proxy_list:
  1458.         if not name or hostonly.endswith(name):
  1459.             if host.endswith(name):
  1460.                 return 1
  1461.     return 0
  1462.  
  1463. if sys.platform == 'darwin':
  1464.     from _scproxy import _get_proxy_settings, _get_proxies
  1465.     
  1466.     def proxy_bypass_macosx_sysconf(host):
  1467.         """
  1468.         Return True iff this host shouldn't be accessed using a proxy
  1469.  
  1470.         This function uses the MacOSX framework SystemConfiguration
  1471.         to fetch the proxy information.
  1472.         """
  1473.         import re
  1474.         import socket
  1475.         fnmatch = fnmatch
  1476.         import fnmatch
  1477.         (hostonly, port) = splitport(host)
  1478.         
  1479.         def ip2num(ipAddr):
  1480.             parts = ipAddr.split('.')
  1481.             parts = map(int, parts)
  1482.             if len(parts) != 4:
  1483.                 parts = parts + [
  1484.                     0,
  1485.                     0,
  1486.                     0,
  1487.                     0][:4]
  1488.             return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3]
  1489.  
  1490.         proxy_settings = _get_proxy_settings()
  1491.         if '.' not in host and proxy_settings['exclude_simple']:
  1492.             return True
  1493.         hostIP = None
  1494.         for value in proxy_settings.get('exceptions', ()):
  1495.             if not value:
  1496.                 continue
  1497.             m = re.match('(\\d+(?:\\.\\d+)*)(/\\d+)?', value)
  1498.             if m is not None:
  1499.                 if hostIP is None:
  1500.                     
  1501.                     try:
  1502.                         hostIP = socket.gethostbyname(hostonly)
  1503.                         hostIP = ip2num(hostIP)
  1504.                     except socket.error:
  1505.                         continue
  1506.                     
  1507.  
  1508.                 base = ip2num(m.group(1))
  1509.                 mask = m.group(2)
  1510.                 if mask is None:
  1511.                     mask = 8 * (m.group(1).count('.') + 1)
  1512.                 else:
  1513.                     mask = int(mask[1:])
  1514.                 mask = 32 - mask
  1515.                 if hostIP >> mask == base >> mask:
  1516.                     return True
  1517.             if fnmatch(host, value):
  1518.                 return True
  1519.         
  1520.         return False
  1521.  
  1522.     
  1523.     def getproxies_macosx_sysconf():
  1524.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1525.  
  1526.         This function uses the MacOSX framework SystemConfiguration
  1527.         to fetch the proxy information.
  1528.         '''
  1529.         return _get_proxies()
  1530.  
  1531.     
  1532.     def proxy_bypass(host):
  1533.         if getproxies_environment():
  1534.             return proxy_bypass_environment(host)
  1535.         return None(host)
  1536.  
  1537.     
  1538.     def getproxies():
  1539.         if not getproxies_environment():
  1540.             pass
  1541.         return getproxies_macosx_sysconf()
  1542.  
  1543. elif os.name == 'nt':
  1544.     
  1545.     def getproxies_registry():
  1546.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1547.  
  1548.         Win32 uses the registry to store proxies.
  1549.  
  1550.         '''
  1551.         proxies = { }
  1552.         
  1553.         try:
  1554.             import _winreg as _winreg
  1555.         except ImportError:
  1556.             return proxies
  1557.  
  1558.         
  1559.         try:
  1560.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1561.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1562.             if proxyEnable:
  1563.                 proxyServer = str(_winreg.QueryValueEx(internetSettings, 'ProxyServer')[0])
  1564.                 if '=' in proxyServer:
  1565.                     for p in proxyServer.split(';'):
  1566.                         (protocol, address) = p.split('=', 1)
  1567.                         import re
  1568.                         if not re.match('^([^/:]+)://', address):
  1569.                             address = '%s://%s' % (protocol, address)
  1570.                         proxies[protocol] = address
  1571.                     
  1572.                 elif proxyServer[:5] == 'http:':
  1573.                     proxies['http'] = proxyServer
  1574.                 else:
  1575.                     proxies['http'] = 'http://%s' % proxyServer
  1576.                     proxies['https'] = 'https://%s' % proxyServer
  1577.                     proxies['ftp'] = 'ftp://%s' % proxyServer
  1578.             internetSettings.Close()
  1579.         except (WindowsError, ValueError, TypeError):
  1580.             pass
  1581.  
  1582.         return proxies
  1583.  
  1584.     
  1585.     def getproxies():
  1586.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1587.  
  1588.         Returns settings gathered from the environment, if specified,
  1589.         or the registry.
  1590.  
  1591.         '''
  1592.         if not getproxies_environment():
  1593.             pass
  1594.         return getproxies_registry()
  1595.  
  1596.     
  1597.     def proxy_bypass_registry(host):
  1598.         
  1599.         try:
  1600.             import _winreg
  1601.             import re
  1602.         except ImportError:
  1603.             return 0
  1604.  
  1605.         
  1606.         try:
  1607.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1608.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1609.             proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0])
  1610.         except WindowsError:
  1611.             return 0
  1612.  
  1613.         if not proxyEnable or not proxyOverride:
  1614.             return 0
  1615.         (rawHost, port) = None(host)
  1616.         host = [
  1617.             rawHost]
  1618.         
  1619.         try:
  1620.             addr = socket.gethostbyname(rawHost)
  1621.             if addr != rawHost:
  1622.                 host.append(addr)
  1623.         except socket.error:
  1624.             pass
  1625.  
  1626.         
  1627.         try:
  1628.             fqdn = socket.getfqdn(rawHost)
  1629.             if fqdn != rawHost:
  1630.                 host.append(fqdn)
  1631.         except socket.error:
  1632.             pass
  1633.  
  1634.         proxyOverride = proxyOverride.split(';')
  1635.         for test in proxyOverride:
  1636.             if test == '<local>' and '.' not in rawHost:
  1637.                 return 1
  1638.             test = test.replace('.', '\\.')
  1639.             test = test.replace('*', '.*')
  1640.             test = test.replace('?', '.')
  1641.             for val in host:
  1642.                 if re.match(test, val, re.I):
  1643.                     return 1
  1644.             
  1645.         
  1646.         return 0
  1647.  
  1648.     
  1649.     def proxy_bypass(host):
  1650.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1651.  
  1652.         Returns settings gathered from the environment, if specified,
  1653.         or the registry.
  1654.  
  1655.         '''
  1656.         if getproxies_environment():
  1657.             return proxy_bypass_environment(host)
  1658.         return None(host)
  1659.  
  1660. else:
  1661.     getproxies = getproxies_environment
  1662.     proxy_bypass = proxy_bypass_environment
  1663.  
  1664. def test1():
  1665.     s = ''
  1666.     for i in range(256):
  1667.         s = s + chr(i)
  1668.     
  1669.     s = s * 4
  1670.     t0 = time.time()
  1671.     qs = quote(s)
  1672.     uqs = unquote(qs)
  1673.     t1 = time.time()
  1674.     if uqs != s:
  1675.         print 'Wrong!'
  1676.     print repr(s)
  1677.     print repr(qs)
  1678.     print repr(uqs)
  1679.     print round(t1 - t0, 3), 'sec'
  1680.  
  1681.  
  1682. def reporthook(blocknum, blocksize, totalsize):
  1683.     print 'Block number: %d, Block size: %d, Total size: %d' % (blocknum, blocksize, totalsize)
  1684.  
  1685.